#include <iostream>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "public.hpp"


class fifo
{
public:
    fifo(const std::string &path = DEFAULT_PATHNAME, const std::string &name = DEFAULTNAME)
        : _path(path), _name(name)
    {
        _fifoname = path + "/" + name;
    }

    ~fifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "fifo deleted" << std::endl;
        }
        else
            ERR("unlink");
    }

    void CreatFifo()
    {
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
            ERR("mkfifo");
        std::cout << "mkfifo succeess" << std::endl;
    }

    void OpenForWrite()
    {
        // 以写方式打开管道文件
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
            ERR("open");
        std::cout << "open for write succeed!" << std::endl;
    }

    //void Write()
    void wakeup()
    {
        int n = 1;
        write(_fd, &n, sizeof(n));
    }

    void OpenForRead()
    {
        // 以读方式打开管道文件
        // 如果write方没有打开管道文件
        // read方就会在open处阻塞
        // 知道有人打开了管道文件，open才返回
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
            ERR("open");
        std::cout << "open for read succeed!" << std::endl;
    }

    //void Read()
    bool wait()
    {
        int n = 0;
        return read(_fd, &n, sizeof(n));
    }

    void Close()
    {
        close(_fd);
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};